package webdev.fragment;

import java.util.ArrayList;

import org.json.JSONArray;

import webdev.adapters.ListAmThucAdapter;
import webdev.database.SQLQuery;
import webdev.dto.DiaDiemDTO;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import dev.danang.R;

public class ListAmThucFragment extends ListFragment {
	
	public static final String TAG = ListAmThucFragment.class.getSimpleName();
	
	// Adapter
	private ListAmThucAdapter mListPlacesAdapter;
	
	private LoadData mLoadData;
	
	private ArrayList<DiaDiemDTO> datas;
	
	
	public ListAmThucFragment() {}
	
	public static ListAmThucFragment newInstance() {
		ListAmThucFragment listAmThuc = new ListAmThucFragment();
        return listAmThuc;
    }
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.list, null);
		init();
		setValue();
		setEvent();
		mLoadData = new LoadData(getActivity());
		mLoadData.execute();
		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	}
	
	private void init() {
		mListPlacesAdapter = new ListAmThucAdapter(getActivity());
		datas = new ArrayList<DiaDiemDTO>();
	}
	
	private void setValue() {
		setListAdapter(mListPlacesAdapter);
	}
	
	private void setEvent() {
	}
	
	/**
	 * Class Asynctask load data
	 */
	private class LoadData extends AsyncTask<Void, Void, Boolean> {
		
		private JSONArray jsonArrayData;
		private DiaDiemDTO place;
		
		private ArrayList<DiaDiemDTO> places;
		
		private SQLQuery db;
		
		public LoadData(Context _context) {
			places = new ArrayList<DiaDiemDTO>();
			db = new SQLQuery(_context);
		}
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}
		
		@Override
		protected Boolean doInBackground(Void... params) {
			try {
				/*JSONObject jsonDataObject = GetData.loadDataJson(getActivity());
				jsonArrayData = jsonDataObject.getJSONArray("AmThuc");
				int leng = jsonArrayData.length();
				for(int i = 0; i < leng ; i++) {
					place = new Places();
					place.parser(jsonArrayData.getJSONObject(i));
					places.add(place);
				}*/
				
				places = db.getAllDiaDiem(SQLQuery.TYPE_FOOD);
				
				return true;
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			return false;
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			if(result) {
				int leng = places.size();
				datas = places;
				for(int i = 0 ; i < leng; i++) {
					mListPlacesAdapter.addData(places.get(i));					
				}
				mListPlacesAdapter.notifyDataSetChanged();
			}
		}
	}

}
